// ignore_for_file: prefer_const_literals_to_create_immutables

part of 'index.dart';

class FriendSearchPage extends StatefulWidget {
  const FriendSearchPage({super.key});

  @override
  State<FriendSearchPage> createState() => _FriendSearchPageState();
}

class _FriendSearchPageState extends State<FriendSearchPage>
    with SingleTickerProviderStateMixin {
  late final _tabController = TabController(length: 2, vsync: this);

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Widget _buildTitle(String text) {
    return Text(
      text,
      style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => FriendSearchProvider(),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: const Color(0xFFFAFAFA),
        body: Consumer<FriendSearchProvider>(
          builder: (context, provider, child) => Column(
            children: [
              Container(
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(Images.bgChatSearch),
                    fit: BoxFit.fill,
                  ),
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Color(0xFFDCD4FF), Color(0xFFFAFAFA)],
                  ),
                ),
                child: Column(
                  children: [
                    _Appbar(
                      controller: provider.controller,
                      onSearch: () => provider._onSearch(null),
                    ),
                    const SizedBox(height: 10),
                    TabBar(
                      controller: _tabController,
                      labelPadding: const EdgeInsets.symmetric(horizontal: 25),
                      tabAlignment: TabAlignment.center,
                      dividerColor: Colors.transparent,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicatorWeight: 1,
                      indicatorPadding: const EdgeInsets.only(
                        bottom: 6,
                        left: 10,
                        right: 10,
                      ),
                      // indicator: UnderlineTabIndicator(
                      //   borderRadius: BorderRadius.circular(99),
                      //   borderSide: const BorderSide(
                      //       width: 3.5, color: Color(0xFF8673F6)),
                      // ),
                      indicator: const CustomTabBarIndicator(),

                      unselectedLabelStyle: const TextStyle(
                        color: Color(0xFFC1C1C1),
                        fontSize: 17,
                      ),
                      labelStyle: const TextStyle(
                        color: Color(0xFF8A72FE),
                        fontWeight: FontWeight.w600,
                        fontSize: 17,
                      ),
                      onTap: (index) => provider.index = index,
                      tabs: [
                        Tab(text: T.current.c_room),
                        Tab(text: T.current.c_user)
                      ],
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    _History(),
                    if (!provider.isSearch)
                      Padding(
                        padding: const EdgeInsets.only(top: 10),
                        child: _buildTitle(T.current.c_top_search),
                      ),
                    const SizedBox(height: 15),
                  ],
                ),
              ),
              TabBarView(
                controller: _tabController,
                physics: const NeverScrollableScrollPhysics(),
                children: [_Rooms(), _Users()],
              ).expanded,
            ],
          ),
        ),
      ),
    );
  }
}

class _History extends StatefulWidget {
  const _History();

  @override
  State<_History> createState() => __HistoryState();
}

class __HistoryState extends State<_History> {
  bool expanded = false;
  final _rowKey = GlobalKey();

  Widget _historyOption(Widget child, {Function()? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.only(right: 10),
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(99),
        ),
        child: child,
      ),
    );
  }

  void _onTap(String value) {
    final provider = context.read<FriendSearchProvider>();
    provider.controller.text = value;
    provider._onSearch(value);
  }

  @override
  Widget build(BuildContext context) {
    List<String> histories = FriendAPI.getHistory();
    if (histories.isEmpty) return const SizedBox();
    final historyItems = histories.reversed
        .map((e) => _historyOption(Text(e), onTap: () => _onTap(e)))
        .toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              T.current.c_history,
              style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
            ),
            Image.asset(Images.icChatClearGrey, width: 30, height: 30),
          ],
        ).onTap(() {
          FriendAPI.clearHistory();
          histories.clear();
          setState(() {});
        }),
        const SizedBox(height: 10),
        LayoutBuilder(
          builder: (context, constraints) {
            if (expanded) {
              return Wrap(
                runSpacing: 10,
                children: [
                  ...historyItems,
                  _historyOption(
                    const Icon(Icons.keyboard_arrow_up,
                        color: Color(0xFFC1C1C1)),
                    onTap: () => setState(() => expanded = false),
                  ),
                ],
              );
            }
            return Row(
              key: _rowKey,
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        ...historyItems,
                      ],
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                _historyOption(
                  const Icon(Icons.keyboard_arrow_down,
                      color: Color(0xFFC1C1C1)),
                  onTap: () {
                    final box = _rowKey.currentContext?.findRenderObject()
                        as RenderBox?;
                    if (box != null) {
                      final hasOverflow =
                          box.size.width >= constraints.maxWidth;
                      if (hasOverflow) {
                        setState(() => expanded = true);
                      }
                    }
                  },
                ),
              ],
            );
          },
        ),
      ],
    );
  }
}

class _Rooms extends StatelessWidget {
  const _Rooms();

  @override
  Widget build(BuildContext context) {
    final provider = context.read<FriendSearchProvider>();
    return provider.rooms.isEmpty
        ? Padding(
            padding: const EdgeInsets.only(bottom: 150),
            child: UnconstrainedBox(
              child: Image.asset(
                Images.bgPlaceEmpty,
                width: 200,
                height: 200,
              ),
            ),
          )
        : CustomPullScrollView(
            controller: provider.roomRefreshController,
            onLoading: provider.onRoomLoading,
            refreshOnStart: false,
            builder: (context, physics) => ListView.builder(
              physics: physics,
              padding: const EdgeInsets.only(bottom: 100),
              itemBuilder: (context, index) {
                return _RoomCard(provider.rooms[index]);
              },
              itemCount: provider.rooms.length,
            ),
          );
  }
}

class _Users extends StatelessWidget {
  const _Users();

  @override
  Widget build(BuildContext context) {
    final provider = context.read<FriendSearchProvider>();
    return provider.users.isEmpty
        ? Padding(
            padding: const EdgeInsets.only(bottom: 150),
            child: UnconstrainedBox(
              child: Image.asset(
                Images.bgPlaceEmpty,
                width: 200,
                height: 200,
              ),
            ),
          )
        : CustomPullScrollView(
            controller: provider.userRefreshController,
            onLoading: provider.onUserLoading,
            refreshOnStart: false,
            builder: (context, physics) => ListView.builder(
              physics: physics,
              padding: const EdgeInsets.only(bottom: 100),
              itemBuilder: (context, index) {
                return _UserCard(provider.users[index]);
              },
              itemCount: provider.users.length,
            ),
          );
  }
}
